{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "**Introduction** ||\n",
        "[Tensors](tensors_deeper_tutorial.html) ||\n",
        "[Autograd](autogradyt_tutorial.html) ||\n",
        "[Building Models](modelsyt_tutorial.html) ||\n",
        "[TensorBoard Support](tensorboardyt_tutorial.html) ||\n",
        "[Training Models](trainingyt.html) ||\n",
        "[Model Understanding](captumyt.html)\n",
        "\n",
        "# Introduction to PyTorch\n",
        "\n",
        "Follow along with the video below or on [youtube](https://www.youtube.com/watch?v=IC0_FRiX-sw)_.\n",
        "\n",
        ".. raw:: html\n",
        "\n",
        "   <div style=\"margin-top:10px; margin-bottom:10px;\">\n",
        "     <iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/IC0_FRiX-sw\" frameborder=\"0\" allow=\"accelerometer; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>\n",
        "   </div>\n",
        "\n",
        "## PyTorch Tensors\n",
        "\n",
        "Follow along with the video beginning at [03:50](https://www.youtube.com/watch?v=IC0_FRiX-sw&t=230s)_.\n",
        "\n",
        "First, we’ll import pytorch.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let’s see a few basic tensor manipulations. First, just a few of the\n",
        "ways to create tensors:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "z = torch.zeros(5, 3)\n",
        "print(z)\n",
        "print(z.dtype)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Above, we create a 5x3 matrix filled with zeros, and query its datatype\n",
        "to find out that the zeros are 32-bit floating point numbers, which is\n",
        "the default PyTorch.\n",
        "\n",
        "What if you wanted integers instead? You can always override the\n",
        "default:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "i = torch.ones((5, 3), dtype=torch.int16)\n",
        "print(i)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "You can see that when we do change the default, the tensor helpfully\n",
        "reports this when printed.\n",
        "\n",
        "It’s common to initialize learning weights randomly, often with a\n",
        "specific seed for the PRNG for reproducibility of results:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "torch.manual_seed(1729)\n",
        "r1 = torch.rand(2, 2)\n",
        "print('A random tensor:')\n",
        "print(r1)\n",
        "\n",
        "r2 = torch.rand(2, 2)\n",
        "print('\\nA different random tensor:')\n",
        "print(r2) # new values\n",
        "\n",
        "torch.manual_seed(1729)\n",
        "r3 = torch.rand(2, 2)\n",
        "print('\\nShould match r1:')\n",
        "print(r3) # repeats values of r1 because of re-seed"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "PyTorch tensors perform arithmetic operations intuitively. Tensors of\n",
        "similar shapes may be added, multiplied, etc. Operations with scalars\n",
        "are distributed over the tensor:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "ones = torch.ones(2, 3)\n",
        "print(ones)\n",
        "\n",
        "twos = torch.ones(2, 3) * 2 # every element is multiplied by 2\n",
        "print(twos)\n",
        "\n",
        "threes = ones + twos       # addition allowed because shapes are similar\n",
        "print(threes)              # tensors are added element-wise\n",
        "print(threes.shape)        # this has the same dimensions as input tensors\n",
        "\n",
        "r1 = torch.rand(2, 3)\n",
        "r2 = torch.rand(3, 2)\n",
        "# uncomment this line to get a runtime error\n",
        "# r3 = r1 + r2"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here’s a small sample of the mathematical operations available:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "r = (torch.rand(2, 2) - 0.5) * 2 # values between -1 and 1\n",
        "print('A random matrix, r:')\n",
        "print(r)\n",
        "\n",
        "# Common mathematical operations are supported:\n",
        "print('\\nAbsolute value of r:')\n",
        "print(torch.abs(r))\n",
        "\n",
        "# ...as are trigonometric functions:\n",
        "print('\\nInverse sine of r:')\n",
        "print(torch.asin(r))\n",
        "\n",
        "# ...and linear algebra operations like determinant and singular value decomposition\n",
        "print('\\nDeterminant of r:')\n",
        "print(torch.det(r))\n",
        "print('\\nSingular value decomposition of r:')\n",
        "print(torch.svd(r))\n",
        "\n",
        "# ...and statistical and aggregate operations:\n",
        "print('\\nAverage and standard deviation of r:')\n",
        "print(torch.std_mean(r))\n",
        "print('\\nMaximum value of r:')\n",
        "print(torch.max(r))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "There’s a good deal more to know about the power of PyTorch tensors,\n",
        "including how to set them up for parallel computations on GPU - we’ll be\n",
        "going into more depth in another video.\n",
        "\n",
        "## PyTorch Models\n",
        "\n",
        "Follow along with the video beginning at [10:00](https://www.youtube.com/watch?v=IC0_FRiX-sw&t=600s)_.\n",
        "\n",
        "Let’s talk about how we can express models in PyTorch\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch                     # for all things PyTorch\n",
        "import torch.nn as nn            # for torch.nn.Module, the parent object for PyTorch models\n",
        "import torch.nn.functional as F  # for the activation function"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. figure:: /_static/img/mnist.png\n",
        "   :alt: le-net-5 diagram\n",
        "\n",
        "*Figure: LeNet-5*\n",
        "\n",
        "Above is a diagram of LeNet-5, one of the earliest convolutional neural\n",
        "nets, and one of the drivers of the explosion in Deep Learning. It was\n",
        "built to read small images of handwritten numbers (the MNIST dataset),\n",
        "and correctly classify which digit was represented in the image.\n",
        "\n",
        "Here’s the abridged version of how it works:\n",
        "\n",
        "-  Layer C1 is a convolutional layer, meaning that it scans the input\n",
        "   image for features it learned during training. It outputs a map of\n",
        "   where it saw each of its learned features in the image. This\n",
        "   “activation map” is downsampled in layer S2.\n",
        "-  Layer C3 is another convolutional layer, this time scanning C1’s\n",
        "   activation map for *combinations* of features. It also puts out an\n",
        "   activation map describing the spatial locations of these feature\n",
        "   combinations, which is downsampled in layer S4.\n",
        "-  Finally, the fully-connected layers at the end, F5, F6, and OUTPUT,\n",
        "   are a *classifier* that takes the final activation map, and\n",
        "   classifies it into one of ten bins representing the 10 digits.\n",
        "\n",
        "How do we express this simple neural network in code?\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class LeNet(nn.Module):\n",
        "\n",
        "    def __init__(self):\n",
        "        super(LeNet, self).__init__()\n",
        "        # 1 input image channel (black & white), 6 output channels, 3x3 square convolution\n",
        "        # kernel\n",
        "        self.conv1 = nn.Conv2d(1, 6, 3)\n",
        "        self.conv2 = nn.Conv2d(6, 16, 3)\n",
        "        # an affine operation: y = Wx + b\n",
        "        self.fc1 = nn.Linear(16 * 6 * 6, 120)  # 6*6 from image dimension\n",
        "        self.fc2 = nn.Linear(120, 84)\n",
        "        self.fc3 = nn.Linear(84, 10)\n",
        "\n",
        "    def forward(self, x):\n",
        "        # Max pooling over a (2, 2) window\n",
        "        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))\n",
        "        # If the size is a square you can only specify a single number\n",
        "        x = F.max_pool2d(F.relu(self.conv2(x)), 2)\n",
        "        x = x.view(-1, self.num_flat_features(x))\n",
        "        x = F.relu(self.fc1(x))\n",
        "        x = F.relu(self.fc2(x))\n",
        "        x = self.fc3(x)\n",
        "        return x\n",
        "\n",
        "    def num_flat_features(self, x):\n",
        "        size = x.size()[1:]  # all dimensions except the batch dimension\n",
        "        num_features = 1\n",
        "        for s in size:\n",
        "            num_features *= s\n",
        "        return num_features"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Looking over this code, you should be able to spot some structural\n",
        "similarities with the diagram above.\n",
        "\n",
        "This demonstrates the structure of a typical PyTorch model: \n",
        "\n",
        "-  It inherits from ``torch.nn.Module`` - modules may be nested - in fact,\n",
        "   even the ``Conv2d`` and ``Linear`` layer classes inherit from\n",
        "   ``torch.nn.Module``.\n",
        "-  A model will have an ``__init__()`` function, where it instantiates\n",
        "   its layers, and loads any data artifacts it might\n",
        "   need (e.g., an NLP model might load a vocabulary).\n",
        "-  A model will have a ``forward()`` function. This is where the actual\n",
        "   computation happens: An input is passed through the network layers\n",
        "   and various functions to generate an output.\n",
        "-  Other than that, you can build out your model class like any other\n",
        "   Python class, adding whatever properties and methods you need to\n",
        "   support your model’s computation.\n",
        "\n",
        "Let’s instantiate this object and run a sample input through it.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "net = LeNet()\n",
        "print(net)                         # what does the object tell us about itself?\n",
        "\n",
        "input = torch.rand(1, 1, 32, 32)   # stand-in for a 32x32 black & white image\n",
        "print('\\nImage batch shape:')\n",
        "print(input.shape)\n",
        "\n",
        "output = net(input)                # we don't call forward() directly\n",
        "print('\\nRaw output:')\n",
        "print(output)\n",
        "print(output.shape)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "There are a few important things happening above:\n",
        "\n",
        "First, we instantiate the ``LeNet`` class, and we print the ``net``\n",
        "object. A subclass of ``torch.nn.Module`` will report the layers it has\n",
        "created and their shapes and parameters. This can provide a handy\n",
        "overview of a model if you want to get the gist of its processing.\n",
        "\n",
        "Below that, we create a dummy input representing a 32x32 image with 1\n",
        "color channel. Normally, you would load an image tile and convert it to\n",
        "a tensor of this shape.\n",
        "\n",
        "You may have noticed an extra dimension to our tensor - the *batch\n",
        "dimension.* PyTorch models assume they are working on *batches* of data\n",
        "- for example, a batch of 16 of our image tiles would have the shape\n",
        "``(16, 1, 32, 32)``. Since we’re only using one image, we create a batch\n",
        "of 1 with shape ``(1, 1, 32, 32)``.\n",
        "\n",
        "We ask the model for an inference by calling it like a function:\n",
        "``net(input)``. The output of this call represents the model’s\n",
        "confidence that the input represents a particular digit. (Since this\n",
        "instance of the model hasn’t learned anything yet, we shouldn’t expect\n",
        "to see any signal in the output.) Looking at the shape of ``output``, we\n",
        "can see that it also has a batch dimension, the size of which should\n",
        "always match the input batch dimension. If we had passed in an input\n",
        "batch of 16 instances, ``output`` would have a shape of ``(16, 10)``.\n",
        "\n",
        "## Datasets and Dataloaders\n",
        "\n",
        "Follow along with the video beginning at [14:00](https://www.youtube.com/watch?v=IC0_FRiX-sw&t=840s)_.\n",
        "\n",
        "Below, we’re going to demonstrate using one of the ready-to-download,\n",
        "open-access datasets from TorchVision, how to transform the images for\n",
        "consumption by your model, and how to use the DataLoader to feed batches\n",
        "of data to your model.\n",
        "\n",
        "The first thing we need to do is transform our incoming images into a\n",
        "PyTorch tensor.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "#%matplotlib inline\n",
        "\n",
        "import torch\n",
        "import torchvision\n",
        "import torchvision.transforms as transforms\n",
        "\n",
        "transform = transforms.Compose(\n",
        "    [transforms.ToTensor(),\n",
        "     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here, we specify two transformations for our input:\n",
        "\n",
        "-  ``transforms.ToTensor()`` converts images loaded by Pillow into \n",
        "   PyTorch tensors.\n",
        "-  ``transforms.Normalize()`` adjusts the values of the tensor so\n",
        "   that their average is zero and their standard deviation is 0.5. Most\n",
        "   activation functions have their strongest gradients around x = 0, so\n",
        "   centering our data there can speed learning.\n",
        "\n",
        "There are many more transforms available, including cropping, centering,\n",
        "rotation, and reflection.\n",
        "\n",
        "Next, we’ll create an instance of the CIFAR10 dataset. This is a set of\n",
        "32x32 color image tiles representing 10 classes of objects: 6 of animals\n",
        "(bird, cat, deer, dog, frog, horse) and 4 of vehicles (airplane,\n",
        "automobile, ship, truck):\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 39,
      "metadata": {
        "collapsed": false
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Files already downloaded and verified\n",
            "Files already downloaded and verified\n",
            "Files already downloaded and verified\n"
          ]
        }
      ],
      "source": [
        "ROOT = \"E:/sfxData/DeepLearning\"\n",
        "\n",
        "trainset100 = torchvision.datasets.CIFAR100(root=ROOT, train=True,\n",
        "                                        download=True, transform=transform)\n",
        "\n",
        "\n",
        "trainset = torchvision.datasets.CIFAR10(root=ROOT, train=True,\n",
        "                                        download=True, transform=transform)\n",
        "\n",
        "test_data = torchvision.datasets.CIFAR10(root=ROOT, train=False,\n",
        "                                        download=True, transform=transform)\n",
        "# print(trainset)\n",
        "# print(trainset.targets)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 43,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "(50000, 32, 32, 3)\n",
            "(50000, 32, 32, 3)\n"
          ]
        }
      ],
      "source": [
        "print(trainset.data.shape)\n",
        "print(trainset100.data.shape)\n",
        "# print(test_data.data)\n",
        "# print(test_data.targets)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div class=\"alert alert-info\"><h4>Note</h4><p>When you run the cell above, it may take a little time for the \n",
        "     dataset to download.</p></div>\n",
        "\n",
        "This is an example of creating a dataset object in PyTorch. Downloadable\n",
        "datasets (like CIFAR-10 above) are subclasses of\n",
        "``torch.utils.data.Dataset``. ``Dataset`` classes in PyTorch include the\n",
        "downloadable datasets in TorchVision, Torchtext, and TorchAudio, as well\n",
        "as utility dataset classes such as ``torchvision.datasets.ImageFolder``,\n",
        "which will read a folder of labeled images. You can also create your own\n",
        "subclasses of ``Dataset``.\n",
        "\n",
        "When we instantiate our dataset, we need to tell it a few things:\n",
        "\n",
        "-  The filesystem path to where we want the data to go. \n",
        "-  Whether or not we are using this set for training; most datasets\n",
        "   will be split into training and test subsets.\n",
        "-  Whether we would like to download the dataset if we haven’t already.\n",
        "-  The transformations we want to apply to the data.\n",
        "\n",
        "Once your dataset is ready, you can give it to the ``DataLoader``:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n",
        "                                          shuffle=True, num_workers=2)\n",
        "\n",
        "# print(trainloader)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "A ``Dataset`` subclass wraps access to the data, and is specialized to\n",
        "the type of data it’s serving. The ``DataLoader`` knows *nothing* about\n",
        "the data, but organizes the input tensors served by the ``Dataset`` into\n",
        "batches with the parameters you specify.\n",
        "\n",
        "In the example above, we’ve asked a ``DataLoader`` to give us batches of\n",
        "4 images from ``trainset``, randomizing their order (``shuffle=True``),\n",
        "and we told it to spin up two workers to load data from disk.\n",
        "\n",
        "It’s good practice to visualize the batches your ``DataLoader`` serves:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "\n",
        "classes = ('plane', 'car', 'bird', 'cat',\n",
        "           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n",
        "\n",
        "def imshow(img):\n",
        "    img = img / 2 + 0.5     # unnormalize\n",
        "    npimg = img.numpy()\n",
        "    plt.imshow(np.transpose(npimg, (1, 2, 0)))\n",
        "\n",
        "\n",
        "# get some random training images\n",
        "dataiter = iter(trainloader)\n",
        "images, labels = next(dataiter)\n",
        "\n",
        "# show images\n",
        "imshow(torchvision.utils.make_grid(images))\n",
        "# print labels\n",
        "print(' '.join('%5s' % classes[labels[j]] for j in range(4)))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Running the above cell should show you a strip of four images, and the\n",
        "correct label for each.\n",
        "\n",
        "## Training Your PyTorch Model\n",
        "\n",
        "Follow along with the video beginning at [17:10](https://www.youtube.com/watch?v=IC0_FRiX-sw&t=1030s)_.\n",
        "\n",
        "Let’s put all the pieces together, and train a model:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "#%matplotlib inline\n",
        "\n",
        "import torch\n",
        "import torch.nn as nn\n",
        "import torch.nn.functional as F\n",
        "import torch.optim as optim\n",
        "\n",
        "import torchvision\n",
        "import torchvision.transforms as transforms\n",
        "\n",
        "import matplotlib\n",
        "import matplotlib.pyplot as plt\n",
        "import numpy as np"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "First, we’ll need training and test datasets. If you haven’t already,\n",
        "run the cell below to make sure the dataset is downloaded. (It may take\n",
        "a minute.)\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "transform = transforms.Compose(\n",
        "    [transforms.ToTensor(),\n",
        "     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n",
        "\n",
        "trainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n",
        "                                        download=True, transform=transform)\n",
        "trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n",
        "                                          shuffle=True, num_workers=2)\n",
        "\n",
        "testset = torchvision.datasets.CIFAR10(root='./data', train=False,\n",
        "                                       download=True, transform=transform)\n",
        "testloader = torch.utils.data.DataLoader(testset, batch_size=4,\n",
        "                                         shuffle=False, num_workers=2)\n",
        "\n",
        "classes = ('plane', 'car', 'bird', 'cat',\n",
        "           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We’ll run our check on the output from ``DataLoader``:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "\n",
        "# functions to show an image\n",
        "\n",
        "\n",
        "def imshow(img):\n",
        "    img = img / 2 + 0.5     # unnormalize\n",
        "    npimg = img.numpy()\n",
        "    plt.imshow(np.transpose(npimg, (1, 2, 0)))\n",
        "\n",
        "\n",
        "# get some random training images\n",
        "dataiter = iter(trainloader)\n",
        "images, labels = next(dataiter)\n",
        "\n",
        "# show images\n",
        "imshow(torchvision.utils.make_grid(images))\n",
        "# print labels\n",
        "print(' '.join('%5s' % classes[labels[j]] for j in range(4)))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This is the model we’ll train. If it looks familiar, that’s because it’s\n",
        "a variant of LeNet - discussed earlier in this video - adapted for\n",
        "3-color images.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class Net(nn.Module):\n",
        "    def __init__(self):\n",
        "        super(Net, self).__init__()\n",
        "        self.conv1 = nn.Conv2d(3, 6, 5)\n",
        "        self.pool = nn.MaxPool2d(2, 2)\n",
        "        self.conv2 = nn.Conv2d(6, 16, 5)\n",
        "        self.fc1 = nn.Linear(16 * 5 * 5, 120)\n",
        "        self.fc2 = nn.Linear(120, 84)\n",
        "        self.fc3 = nn.Linear(84, 10)\n",
        "\n",
        "    def forward(self, x):\n",
        "        x = self.pool(F.relu(self.conv1(x)))\n",
        "        x = self.pool(F.relu(self.conv2(x)))\n",
        "        x = x.view(-1, 16 * 5 * 5)\n",
        "        x = F.relu(self.fc1(x))\n",
        "        x = F.relu(self.fc2(x))\n",
        "        x = self.fc3(x)\n",
        "        return x\n",
        "\n",
        "\n",
        "net = Net()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The last ingredients we need are a loss function and an optimizer:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "criterion = nn.CrossEntropyLoss()\n",
        "optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The loss function, as discussed earlier in this video, is a measure of\n",
        "how far from our ideal output the model’s prediction was. Cross-entropy\n",
        "loss is a typical loss function for classification models like ours.\n",
        "\n",
        "The **optimizer** is what drives the learning. Here we have created an\n",
        "optimizer that implements *stochastic gradient descent,* one of the more\n",
        "straightforward optimization algorithms. Besides parameters of the\n",
        "algorithm, like the learning rate (``lr``) and momentum, we also pass in\n",
        "``net.parameters()``, which is a collection of all the learning weights\n",
        "in the model - which is what the optimizer adjusts.\n",
        "\n",
        "Finally, all of this is assembled into the training loop. Go ahead and\n",
        "run this cell, as it will likely take a few minutes to execute:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "for epoch in range(2):  # loop over the dataset multiple times\n",
        "\n",
        "    running_loss = 0.0\n",
        "    for i, data in enumerate(trainloader, 0):\n",
        "        # get the inputs\n",
        "        inputs, labels = data\n",
        "\n",
        "        # zero the parameter gradients\n",
        "        optimizer.zero_grad()\n",
        "\n",
        "        # forward + backward + optimize\n",
        "        outputs = net(inputs)\n",
        "        loss = criterion(outputs, labels)\n",
        "        loss.backward()\n",
        "        optimizer.step()\n",
        "\n",
        "        # print statistics\n",
        "        running_loss += loss.item()\n",
        "        if i % 2000 == 1999:    # print every 2000 mini-batches\n",
        "            print('[%d, %5d] loss: %.3f' %\n",
        "                  (epoch + 1, i + 1, running_loss / 2000))\n",
        "            running_loss = 0.0\n",
        "\n",
        "print('Finished Training')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here, we are doing only **2 training epochs** (line 1) - that is, two\n",
        "passes over the training dataset. Each pass has an inner loop that\n",
        "**iterates over the training data** (line 4), serving batches of\n",
        "transformed input images and their correct labels.\n",
        "\n",
        "**Zeroing the gradients** (line 9) is an important step. Gradients are\n",
        "accumulated over a batch; if we do not reset them for every batch, they\n",
        "will keep accumulating, which will provide incorrect gradient values,\n",
        "making learning impossible.\n",
        "\n",
        "In line 12, we **ask the model for its predictions** on this batch. In\n",
        "the following line (13), we compute the loss - the difference between\n",
        "``outputs`` (the model prediction) and ``labels`` (the correct output).\n",
        "\n",
        "In line 14, we do the ``backward()`` pass, and calculate the gradients\n",
        "that will direct the learning.\n",
        "\n",
        "In line 15, the optimizer performs one learning step - it uses the\n",
        "gradients from the ``backward()`` call to nudge the learning weights in\n",
        "the direction it thinks will reduce the loss.\n",
        "\n",
        "The remainder of the loop does some light reporting on the epoch number,\n",
        "how many training instances have been completed, and what the collected\n",
        "loss is over the training loop.\n",
        "\n",
        "**When you run the cell above,** you should see something like this:\n",
        "\n",
        "::\n",
        "\n",
        "   [1,  2000] loss: 2.235\n",
        "   [1,  4000] loss: 1.940\n",
        "   [1,  6000] loss: 1.713\n",
        "   [1,  8000] loss: 1.573\n",
        "   [1, 10000] loss: 1.507\n",
        "   [1, 12000] loss: 1.442\n",
        "   [2,  2000] loss: 1.378\n",
        "   [2,  4000] loss: 1.364\n",
        "   [2,  6000] loss: 1.349\n",
        "   [2,  8000] loss: 1.319\n",
        "   [2, 10000] loss: 1.284\n",
        "   [2, 12000] loss: 1.267\n",
        "   Finished Training\n",
        "\n",
        "Note that the loss is monotonically descending, indicating that our\n",
        "model is continuing to improve its performance on the training dataset.\n",
        "\n",
        "As a final step, we should check that the model is actually doing\n",
        "*general* learning, and not simply “memorizing” the dataset. This is\n",
        "called **overfitting,** and usually indicates that the dataset is too\n",
        "small (not enough examples for general learning), or that the model has\n",
        "more learning parameters than it needs to correctly model the dataset.\n",
        "\n",
        "This is the reason datasets are split into training and test subsets -\n",
        "to test the generality of the model, we ask it to make predictions on\n",
        "data it hasn’t trained on:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "correct = 0\n",
        "total = 0\n",
        "with torch.no_grad():\n",
        "    for data in testloader:\n",
        "        images, labels = data\n",
        "        outputs = net(images)\n",
        "        _, predicted = torch.max(outputs.data, 1)\n",
        "        total += labels.size(0)\n",
        "        correct += (predicted == labels).sum().item()\n",
        "\n",
        "print('Accuracy of the network on the 10000 test images: %d %%' % (\n",
        "    100 * correct / total))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "If you followed along, you should see that the model is roughly 50%\n",
        "accurate at this point. That’s not exactly state-of-the-art, but it’s\n",
        "far better than the 10% accuracy we’d expect from a random output. This\n",
        "demonstrates that some general learning did happen in the model.\n",
        "\n",
        "\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)]"
    },
    "vscode": {
      "interpreter": {
        "hash": "cf18841ace8313d0bc088ca146c17a6c0040e82121d5cb75c0ea07172309253d"
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
